//
//  MYGFindDetailController.swift
//  MYGrow
//
//  Created by 小火科技 on 2024/3/12.
//

import UIKit
import MJRefresh

class MYGFindDetailController: MYGBaseController {
    private var model: MYGFindDetailModel = MYGFindDetailModel() {
        didSet {
            footerView.likeButton.isSelected = model.post.is_like == 1
            footerView.starButton.isSelected = model.post.is_collects == 1
            
            if model.post.type == 2 {
                playVideo()
            }
        }
    }
    
    var comments: [MYGFindDetailComment] = []
    
    private var page = 1
    let id: Int
    
    init(id: Int) {
        self.id = id
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        configUI()
        
        tableView.mj_header?.beginRefreshing()
    }
    
    // MARK: - UI
    private func configUI() {
        title = "动态详情"
        view.backgroundColor = .white
        view.addSubview(tableView)
        view.addSubview(footerView)
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalTo(footerView.snp.top)
        }
        
        footerView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.bottom.equalToSuperview().inset(bottomSafeheight)
            make.height.equalTo(46)
        }
    }
    
    private func playVideo() {
        guard let videoUrl = URL(string: model.post.medias.first ?? "") else {
            return
        }
//        self.playerManager.assetURL = videoUrl
//        let playerItem = AVPlayerItem(url: videoUrl!)
//        player.replaceCurrentItem(with: playerItem)
//        player.play()
        avPlayer.url = videoUrl
        avPlayer.play()

    }
    
    // MARK: - lazy load
    private lazy var tableView: UITableView = {
        let tableView = UITableView()
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        tableView.register(cellWithClass: MYGFindDetailCell.self)
        tableView.register(cellWithClass: MYGHeadDetailHeaderCell.self)
        tableView.register(cellWithClass: MYGHeadDetailCommentCell.self)
        
        tableView.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getDetail()
        })
        
        tableView.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getDetail()
        })
        return tableView
    }()
    
    private lazy var avPlayer: CLPlayer = {
        let view = CLPlayer(frame: .zero) { config in
            config.rotateStyle = .none
        }
        
        return view
    }()
    
    private lazy var footerView: MYGHeadDetailFooterView = {
        let view = MYGHeadDetailFooterView()
        view.remarkAction = {[weak self] in
            guard let self = self else {
                return
            }
            let alert = UIAlertController(title: "提示", message: "请输入评论内容", preferredStyle: .alert)
            alert.addTextField { tf in
                tf.placeholder = "请输入评论内容"
            }
            
            let okey = UIAlertAction(title: "确定", style: .default) { _ in
                alert.dismiss(animated: true)
                guard let text = alert.textFields?.first?.text, !text.isEmpty else {
                    return
                }
                
                self.comment(text, parent_id: nil)
            }
            
            let cancel = UIAlertAction(title: "取消", style: .cancel)
            alert.addAction(okey)
            alert.addAction(cancel)
            
            self.present(alert, animated: true)
        }
        
        view.likeAction = {[weak self] in
            guard let self = self else {
                return
            }
            
            let isLike = self.model.post.is_like
            self.like(type: 7, status: isLike == 0, id: self.model.post.id)
        }
        
        view.starAction = {[weak self] in
            guard let self = self else {
                return
            }
            
            self.collect()
        }
        return view
    }()
}

extension MYGFindDetailController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        comments.count + 2
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.row == 0 {
            let cell = tableView.dequeueReusableCell(withClass: MYGFindDetailCell.self, for: indexPath)
            cell.model = model.post
            if model.post.type == 2 {
                cell.pagerView.addSubview(avPlayer)
                
                avPlayer.snp.remakeConstraints { make in
                    make.edges.equalToSuperview()
                }
            }
            cell.clickImageBlock = { [self] in
                var images = [SKPhoto]()
                for (_,obj)in self.model.post.medias.enumerated() {
                    let photo = SKPhoto.photoWithImageURL(obj)
                    photo.shouldCachePhotoURLImage = true
                    images.append(photo)
                }
                SKPhotoBrowserOptions.displayAction = false
                let browser = SKPhotoBrowser.init(photos: images, initialPageIndex: indexPath.row)
                self.present(browser, animated: true)
                
            }
            return cell
        } else if indexPath.row == 1 {
            let cell = tableView.dequeueReusableCell(withClass: MYGHeadDetailHeaderCell.self, for: indexPath)
            cell.nameLabel.text = "\(self.model.comment.page.total)条评论"
            return cell
        }
        
        let cell = tableView.dequeueReusableCell(withClass: MYGHeadDetailCommentCell.self, for: indexPath)
        let item = comments[indexPath.row-2]
        cell.model = item
        cell.likeAction = {[weak self] in
            self?.like(type: 9, status: item.is_like == 0, id: item.id)
        }
        cell.commentAction = {[weak self] in
            guard let self = self else {
                return
            }
            let alert = UIAlertController(title: "提示", message: "请输入评论内容", preferredStyle: .alert)
            alert.addTextField { tf in
                tf.placeholder = "请输入评论内容"
            }
            
            let okey = UIAlertAction(title: "确定", style: .default) { _ in
                alert.dismiss(animated: true)
                guard let text = alert.textFields?.first?.text, !text.isEmpty else {
                    return
                }
                
                self.comment(text, parent_id: item.id)
            }
            
            let cancel = UIAlertAction(title: "取消", style: .cancel)
            alert.addAction(okey)
            alert.addAction(cancel)
            
            self.present(alert, animated: true)
        }
        return cell
    }
}

extension MYGFindDetailController {
    private func getDetail() {
        MMYGNetwork<MYGFindAPI, MYGFindDetailModel>.request(target: .detail(id: id, page: page)) { item in
            guard let item = item else {
                return
            }
            self.tableView.mj_header?.endRefreshing()
            
            if item.comment.page.page == 1 {
                self.model = item
            } else {
                self.model.comment.list.append(contentsOf: item.comment.list)
            }
            
            if self.model.comment.page.total <= self.model.comment.list.count {
                self.tableView.mj_footer?.endRefreshingWithNoMoreData()
            } else {
                self.tableView.mj_footer?.endRefreshing()
            }
            
            self.comments = []
            for model in self.model.comment.list {
                self.comments.append(model)
                model.isSecond = false
                if model.reply.count > 0 {
                    self.getComments(model)
                }
            }
            self.tableView.reloadData()
        } failed: { _, error in
            self.tableView.mj_header?.endRefreshing()
            self.tableView.mj_footer?.endRefreshing()
            
            MMYGHUD.showToast(text: error)
        }

    }
    
    private func comment(_ text: String, parent_id: Int?) {
        MYGLoading.show()
        MYGNetwork<MYGFindAPI, MYGEmptyModel>.request(target: .comment(post_id: model.post.id, content: text, parent_id: parent_id)) { _ in
            MYGLoading.hide()
            self.tableView.mj_header?.beginRefreshing()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    private func like(type: Int, status: Bool, id: Int) {
        MYGLoading.show()
        MYGNetwork<MYGFindAPI, MYGEmptyModel>.request(target: .like(type: type, status: status ? 1 : 0, id: id)) { _ in
            MYGLoading.hide()
            if type == 7 {
                self.model.post.is_like = status ? 1 : 0
                self.footerView.likeButton.isSelected = status
            } else {
                for item in self.model.comment.list {
                    if item.id == id {
                        item.is_like = status ? 1 : 0
                        if status {
                            item.likes += 1
                        } else {
                            item.likes -= 1
                        }
                        break
                    }
                }
                
                self.tableView.reloadData()
            }
            

        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    private func collect() {
        let collect = model.post.is_collects == 0 ? 1 : 0
        MYGLoading.show()
        MYGNetwork<MYGMeAPI, MYGEmptyModel>.request(target: .collectSubmit(param: [
            "data_id":"\(id)",
           "type":"7",
            "collect_status":collect])) { _ in
            MYGLoading.hide()
            self.model.post.is_collects = collect
            self.footerView.starButton.isSelected = collect == 1
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func getComments(_ model: MYGFindDetailComment) {
        for item in model.reply {
            comments.append(item)
            if item.reply.count > 0 {
                getComments(item)
            }
        }
    }
}
